package com.iot.ammeter.controller.other;

import com.iot.ammeter.anno.LogAnnotation;
import com.iot.ammeter.dto.web.email.CheckEmail;
import com.iot.ammeter.responseResult.ResponseResult;
import com.iot.ammeter.service.other.SendEmailService;
import com.iot.ammeter.utils.CheckTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName: OtherController
 * @Author: Basil
 * @Date: 2021/9/26 下午3:20
 * @Version: 1.0
 * @Description： 定义发送验证码接口
 **/
@RestController
@Api(tags = "邮件服务类")
@RequestMapping("/api/email")
public class EmailController {


    private final SendEmailService emailService;

    /**
     * 方法注入service服务
     *
     * @param emailService 邮件服务
     */
    public EmailController(SendEmailService emailService) {
        this.emailService = emailService;
    }

    /**
     * 发送邮件验证码
     *
     * @param email 邮箱号
     * @param type  邮件类型
     *              1：注册验证码邮件
     *              2：重置密码验证码邮件
     * @return 发送邮件验证码成功或者失败
     */
    @ApiOperation(value = "发送邮件验证码")
    @LogAnnotation(module = "SendEmailCaptcha", operator = "发送邮件验证码")
    @PostMapping("/email_captcha")
    public ResponseResult sendEmailCaptcha(@RequestParam("email") String email, @RequestParam String type) {
        return ResponseResult.SUCCESS(emailService.sendEmailCaptcha(email, type));
    }

    /**
     * 校验邮件验证码是否正确
     *
     * @param checkEmail 邮件验证码及邮箱
     *                   type取值：
     *                   1：注册验证码，2：重置密码验证码，3：更换邮箱验证码
     * @return 校验成功或失败信息
     */
    @ApiOperation(value = "校验邮件验证码是否正确")
    @LogAnnotation(module = "verifyCaptcha", operator = "校验邮件验证码是否正确")
    @PostMapping("/check")
    public ResponseResult verifyCaptcha(@RequestBody CheckEmail checkEmail) {
        if (checkEmail.getEmail() == null || checkEmail.getCaptcha() == null || checkEmail.getType() == null) {
            return ResponseResult.FAILED("验证码或邮箱不能为空");
        }
        if (!CheckTool.isEmail(checkEmail.getEmail().trim())) {
            return ResponseResult.FAILED("邮箱格式有误");
        }
        return emailService.verifyCaptcha(checkEmail) ? ResponseResult.SUCCESS("验证码正确") :
                ResponseResult.FAILED("验证码错误");
    }
}
